Strings in JavaScript are used to store and manipulate text. They are a sequence of characters enclosed in single quotes, double quotes, or backticks.
Strings can be created using single quotes, double quotes, or backticks (template literals):
let singleQuoteString = 'Hello, World!';
let doubleQuoteString = "Hello, World!";
let templateLiteralString = `Hello, World!`;
The length
property returns the length of a string:
let text = "Hello, World!";
console.log(text.length); // Outputs: 13
Escape characters are used to include special characters in a string:
let text = "He said, \"Hello!\"";
let singleQuote = 'It\'s a beautiful day!';
let backslash = "This is a backslash: \\";
Javascript strings are primitive and immutable: All string methods produce a new string without altering the original
string.
JavaScript provides various methods to work with strings:
let text = "Hello, World!";
console.log(text.charAt(0)); // Outputs: H
console.log(text.concat(" How are you?")); // Outputs: Hello, World! How are you?
console.log(text.includes("World")); // Outputs: true
console.log(text.indexOf("World")); // Outputs: 7
console.log(text.slice(0, 5)); // Outputs: Hello
console.log(text.toLowerCase()); // Outputs: hello, world!
console.log(text.toUpperCase()); // Outputs: HELLO, WORLD!
console.log(text.trim()); // Outputs: Hello, World!
Template literals allow for embedded expressions and multi-line strings:
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Outputs: Hello, Alice!
let multiLineString = `This is a string
that spans multiple
lines.`;
console.log(multiLineString);